package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.adapter.OrgAdapter;
import com.example.chuntiao.cophook.adapter.OrgManageAdapter;
import com.example.chuntiao.cophook.beans.Org;
import com.example.chuntiao.cophook.beans.OrgDataSupport;
import com.example.chuntiao.cophook.enums.ResultState;
import com.example.chuntiao.cophook.enums.UpdateState;
import com.example.chuntiao.cophook.exception.LogInException;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.example.chuntiao.cophook.mytools.MyApp;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;

public class ManageOrgActi extends AppCompatActivity {

    private final static int REQ_FRO_crop=1;
    private final static int REQ_FOR_CHOOSE_ACTI=2;
    private final static int REQ_NEW_ORG=3;

    RecyclerView recyclerView;
    OrgManageAdapter mAdapter;
    Boolean [] changed;

    private Integer pos=null;
    MyApp mApp;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_FOR_CHOOSE_ACTI:
                if (resultCode == RESULT_OK) {
                    Uri uri = null;
                    if (data != null) {
                        uri = data.getData();
                        cropPhoto(uri);
                    }
                }
                break;
            case REQ_FRO_crop:
                if (resultCode == RESULT_OK) {

                    Bundle bundle = data.getExtras();
                    final Bitmap bitmap = bundle.getParcelable("data");
                    new AsyncTask<Void,Void,Boolean>(){
                        AlertDialog alert;
                        @Override
                        protected void onPreExecute() {
                            alert = new AlertDialog.Builder(ManageOrgActi.this)
                                    .setMessage("未知错误")
                                    .setPositiveButton(R.string.yse, null)
                                    .create();
                        }

                        @Override
                        protected Boolean doInBackground(Void... params) {
                            try {
                                int imgVer = HttpTool.sendOkHttpUpload(ManageOrgActi.this, bitmap, HttpTool.UPLOAD_OEG_IMG,mAdapter.getmOrgList().get(pos).getOid());
                                mAdapter.getmOrgList().get(pos).setImgVer(imgVer);
                                return true;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return false;
                        }

                        @Override
                        protected void onPostExecute(Boolean result) {
                            if(!result){
                                alert.show();
                            }
                            else {
                                changed[1]=true;
                                alert=null;
                            }
                        }
                    }.execute();

                }
                break;
            case REQ_NEW_ORG:
                if(resultCode==RESULT_OK){
                    mApp.setNextUpdate();
                    finish();
                }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_rec_with_fab);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        recyclerView=(RecyclerView)findViewById(R.id.rec_list);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        final FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ManageOrgActi.this,NewOrgActivity.class);
                startActivityForResult(intent,REQ_NEW_ORG);
            }
        });

        setTitle("管理");
        mApp=(MyApp) getApplication();
        mAdapter =new OrgManageAdapter(true);
        LinearLayoutManager layoutManager=new LinearLayoutManager(ManageOrgActi.this);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter.setOnClickListener(new OrgManageAdapter.OnOrgClickListener() {
            @Override
            public void onClickPic(View v, int position) {

            }

            @Override
            public void onClickMore(View v, final int position) {
                changed=new Boolean[]{false,false};

                final Org o= mAdapter.getmOrgList().get(position);
                pos=position;
                BottomDialog bottomDialog=new BottomDialog(ManageOrgActi.this,R.layout.bottom_dialog_org);

                View rootView=bottomDialog.getRootView();
                //获取 bottomDialog 的所有子控件
                LinearLayout layoutOpenState=(LinearLayout) rootView.findViewById(R.id.layout_org_state);
                LinearLayout layoutPic=(LinearLayout)rootView.findViewById(R.id.layout_pic);
                LinearLayout layoutOname=(LinearLayout)rootView.findViewById(R.id.layout_oname);
                LinearLayout layoutIntro=(LinearLayout)rootView.findViewById(R.id.layout_intro);

                Switch switchState=(Switch)rootView.findViewById(R.id.switch_open_state);
                final TextView txtOname=(TextView)rootView.findViewById(R.id.txt_oname);
                final TextView txtIntro=(TextView)rootView.findViewById(R.id.txt_intro);

                switchState.setChecked(o.isOpen());
                switchState.setText(o.isOpen()? "开放":"关闭");
                switchState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        o.setOpen(isChecked);
                        buttonView.setText(isChecked? "开放":"关闭");
                        changed[0]=true;
                    }
                });

                txtOname.setText(o.getOname());
                String intro=o.getIntro();
                if(!"".equals(intro)){
                    txtIntro.setVisibility(View.VISIBLE);
                    txtIntro.setText(o.getIntro());
                }

                layoutPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, REQ_FOR_CHOOSE_ACTI);
                    }
                });

                final InputDialog dialogOname=new InputDialog(ManageOrgActi.this//这些对话框是在 bottomDialog 的各种子控件的基础上弹出的
                        ,"名称",txtOname,changed);
                layoutOname.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogOname.setText(txtOname.getText());
                        dialogOname.setSelection(txtOname.length());
                        dialogOname.show();
                    }
                });

                final InputDialog dialogIntro=new InputDialog(ManageOrgActi.this//这些对话框是在 bottomDialog 的各种子控件的基础上弹出的
                        ,"简介",txtIntro,changed);
                layoutIntro.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogIntro.setText(txtIntro.getText());
                        dialogIntro.setSelection(txtIntro.length());
                        dialogIntro.show();
                    }
                });

                bottomDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if(changed[0]){
                            o.setOname(txtOname.getText().toString());
                            o.setIntro(txtIntro.getText().toString());
                            new AsyncTask<Void,Void,Boolean>(){
                                AlertDialog alertDialog;

                                @Override
                                protected void onPreExecute() {
                                    alertDialog=new AlertDialog.Builder(ManageOrgActi.this)
                                            .setPositiveButton(R.string.yse,null)
                                            .create();
                                }

                                @Override
                                protected Boolean doInBackground(Void... params) {

                                    try {
                                        UpdateState state= HttpTool.sendOkHttpUpDateOrg(ManageOrgActi.this
                                                ,HttpTool.CODE_UPDATE_ORG,o,0);
                                        return state!=UpdateState.FAIL;
                                    }catch (LogInException e){
                                        e.printStackTrace();
                                        alertDialog.setMessage("自动登录失败");
                                    }
                                    catch (ConnectException e){
                                        e.printStackTrace();
                                        alertDialog.setMessage("网络错误");
                                    }
                                    catch (IOException e) {
                                        e.printStackTrace();
                                        alertDialog.setMessage("未知错误");
                                    }
                                    return false;
                                }

                                @Override
                                protected void onPostExecute(Boolean result) {
                                    if(!result){
                                        alertDialog.show();
                                    }
                                    else {
                                        mAdapter.notifyItemChanged(position);
                                        mApp.setNextUpdate();//使得 MainActivity 更新本地数据库
                                        alertDialog=null;
                                        Snackbar.make(fab,"信息更新完成",Snackbar.LENGTH_SHORT).show();
                                    }
                                }
                            }.execute();
                        }

                        if(changed[1]){
                            mAdapter.notifyItemChanged(position);
                        }

                    }
                });
                bottomDialog.show();
            }
        });

        recyclerView.setAdapter(mAdapter);
        new AsyncTask<Void,Void,ArrayList<Org>>(){
            @Override
            protected ArrayList<Org> doInBackground(Void... params) {

                ArrayList<OrgDataSupport> orgDataSupports=
                        (ArrayList<OrgDataSupport>) DataSupport.where("superu=?",mApp.getUid()).find(OrgDataSupport.class);
                ArrayList<Org> orgs=new ArrayList<>();
                for (OrgDataSupport o:orgDataSupports) {
                    orgs.add(new Org(o));
                }
                return orgs;
            }

            @Override
            protected void onPostExecute(ArrayList<Org> arrayList) {
                mAdapter.setmOrgList(arrayList);
                mAdapter.notifyDataSetChanged();
            }
        }.execute();

    }

    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 2.2);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 330);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQ_FRO_crop);
    }

}
